package com.wanjia.bpsapi.service.jkmc;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.wanjia.bpsapi.pojo.dto.jkmc.UserVege;
import com.wanjia.bpsapi.properties.TimedTaskProperties;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class JkService {

    private static final String UID_IS_NULL = "uid不能为空";
    private static final String PRODUCT_ID_IS_NULL = "商品id不能为空";
    private static final String PRICE_IS_NULL = "价格不能为空";
    private static final String SUK_IS_NULL = "商品规格不能为空";
    private static final String STOCK_IS_NULL = "商品库存不能为空";

    @Setter(onMethod_ = @Autowired)
    private RestTemplate restTemplate;

    @Setter(onMethod_ = @Autowired)
    private TimedTaskProperties properties;

    public List<UserVege> getList(Long uid) {
        // 参数校验
        if (uid == null) {
            throw new NullPointerException(UID_IS_NULL);
        }

        // 请求
        String url = properties.getGetUserVegeListUrl() + "?uid=" + uid;
        RequestEntity<Void> request = RequestEntity.get(url)
                .header("Token", properties.getToken())
                .build();
        ResponseEntity<String> entity = restTemplate.exchange(request, String.class);

        // 结果解析
        return Optional.of(entity)
                .filter(HttpEntity::hasBody)
                .map(HttpEntity::getBody)
                .filter(StrUtil::isNotBlank)
                .map(JSONUtil::parseObj)
                .filter(j -> j.getInt("code") == 1)
                .map(j -> j.getJSONObject("data"))
                .map(j -> j.getJSONArray("list"))
                .map(j -> j.toList(UserVege.class))
                .orElseThrow(RuntimeException::new);
    }

    public void addUserVege(Long uid, Long... productIds) {
        // 参数校验
        if (uid == null) {
            throw new NullPointerException(UID_IS_NULL);
        }
        if (ArrayUtil.isEmpty(productIds)) {
            return;
        }

        // 请求
        String url = properties.getAddUserVegeUrl();
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("uid", uid);
        for (int i = 0; i < productIds.length; i++) {
            body.add("product_ids[" + i + "]", productIds[i]);
        }
        RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity.post(url)
                .header("Token", properties.getToken())
                .body(body);
        ResponseEntity<String> entity = restTemplate.exchange(requestEntity, String.class);

        // 结果解析
        Optional.of(entity)
                .filter(HttpEntity::hasBody)
                .map(HttpEntity::getBody)
                .filter(StrUtil::isNotBlank)
                .map(JSONUtil::parseObj)
                .filter(j -> j.getInt("code") == 1)
                .orElseThrow(RuntimeException::new);
    }

    public void updateVegePrice(Long uid, Long productId, String suk, BigDecimal price) {
        // 参数校验
        if (uid == null) {
            throw new NullPointerException(UID_IS_NULL);
        }
        if (productId == null) {
            throw new NullPointerException(PRODUCT_ID_IS_NULL);
        }
        if (price == null) {
            throw new NullPointerException(PRICE_IS_NULL);
        }

        // 请求
        String url = properties.getUpdateUserVegePriceUrl();
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("uid", uid);
        body.add("product_id", productId);
        body.add("price", price);
        body.add("suk", suk);
        RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity.post(url)
                .header("Token", properties.getToken())
                .body(body);
        ResponseEntity<String> entity = restTemplate.exchange(requestEntity, String.class);

        // 结果解析
        Optional.of(entity)
                .filter(HttpEntity::hasBody)
                .map(HttpEntity::getBody)
                .filter(StrUtil::isNotBlank)
                .map(JSONUtil::parseObj)
                .filter(j -> j.getInt("code") == 1)
                .orElseThrow(RuntimeException::new);
    }

    public void deleteUserVege(Long uid, Long... productIds) {
        // 参数校验
        if (uid == null) {
            throw new NullPointerException(UID_IS_NULL);
        }
        if (ArrayUtil.isEmpty(productIds)) {
            return;
        }

        // 请求
        List<UserVege> veges = getList(uid);
        List<Long> ids = veges.stream()
                .filter(v -> ArrayUtil.contains(productIds, v.getProductId()))
                .map(UserVege::getId)
                .collect(Collectors.toList());
        deleteUserVege(ids);
    }

    private void deleteUserVege(List<Long> ids) {
        // 参数校验
        if (ArrayUtil.isEmpty(ids)) {
            return;
        }

        // 请求
        String url = properties.getDelUserUrl() + "?ids=" + ids.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(","));
        RequestEntity<Void> requestEntity = RequestEntity.get(url)
                .header("Token", properties.getToken())
                .build();
        ResponseEntity<String> entity = restTemplate.exchange(requestEntity, String.class);

        // 结果解析
        Optional.of(entity)
                .filter(HttpEntity::hasBody)
                .map(HttpEntity::getBody)
                .filter(StrUtil::isNotBlank)
                .map(JSONUtil::parseObj)
                .filter(j -> j.getInt("code") == 1)
                .orElseThrow(RuntimeException::new);
    }

    public void updateVegeStock(Long productId, String suk, Long stock) {
        // 参数校验
        if (productId == null) {
            throw new NullPointerException(PRODUCT_ID_IS_NULL);
        }
        if (suk == null) {
            throw new NullPointerException(SUK_IS_NULL);
        }
        if (stock == null) {
            throw new NullPointerException(STOCK_IS_NULL);
        }

        // 请求
        String url = properties.getUpdateUserVegeStockUrl();
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("product_id", productId);
        body.add("suk", suk);
        body.add("stock", stock);
        RequestEntity<MultiValueMap<String, Object>> requestEntity = RequestEntity.post(url)
                .header("Token", properties.getToken())
                .body(body);
        ResponseEntity<String> entity = restTemplate.exchange(requestEntity, String.class);

        // 结果解析
        Optional.of(entity)
                .filter(HttpEntity::hasBody)
                .map(HttpEntity::getBody)
                .filter(StrUtil::isNotBlank)
                .map(JSONUtil::parseObj)
                .filter(j -> j.getInt("code") == 1)
                .orElseThrow(RuntimeException::new);
    }
}
